package com.queen.testretrofitrxjava.applications;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import com.queen.testretrofitrxjava.BuildConfig;
import com.queen.testretrofitrxjava.internal.di.components.ApplicationComponent;
import com.queen.testretrofitrxjava.internal.di.components.DaggerApplicationComponent;
import com.queen.testretrofitrxjava.internal.di.modules.ApplicationModule;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liukun on 16/3/8.
 */
public class ApplicationController extends Application {

    public static final String TAG = ApplicationController.class.getSimpleName();

    private static ApplicationController sInstance;

    private List<Activity> activityList = new ArrayList<Activity>();

    private ApplicationComponent component;

    @Override
    public void onCreate() {

        super.onCreate();

        sInstance = this;

        component = DaggerApplicationComponent
                .builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    public ApplicationComponent getApplicationComponent(){
        return component;
    }

    public static synchronized ApplicationController getsInstance(){
        return sInstance;
    }


    public void addActivity(Activity activity){
        activityList.add(activity);
    }

    public void deleteActivity(Activity activity){
        activityList.remove(activity);
    }

    public List<Activity> getActivityList(){
        return activityList;
    }

    public Activity getCurrentActivity(){
        if (null != activityList && activityList.size() > 0) {
            return activityList.get(activityList.size()-1);
        }
        return null;
    }

    @Override
    public void onTerminate() {
        if (BuildConfig.DEBUG){
            Log.d(TAG, "onTerminate");
        }
        super.onTerminate();

        for (Activity activity : activityList) {
            if (activity != null) {
                activity.finish();
            }
        }

        System.exit(0);
    }
}
